package com.ncmmall.application.business.live;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.ncmmall.application.business.order.wechat.WechatRefundRequest;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.live.LiveBalanceRecord;
import com.ncmmall.domain.business.live.LiveBalanceRecordRepository;
import com.ncmmall.domain.business.live.LiveWithdraw;
import com.ncmmall.domain.business.live.LiveWithdrawPayRecord;
import com.ncmmall.domain.business.live.LiveWithdrawPayRecordRepository;
import com.ncmmall.domain.business.live.LiveWithdrawRepository;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 直播提现管理
 */
@Service
@Transactional
@Slf4j
public class LiveWithdrawApplication {

    @Autowired
    private LiveWithdrawRepository liveWithdrawRepository;

    @Autowired
    private WebUserRepository webUserRepository;

    @Autowired
    private LiveWithdrawPayRecordRepository liveWithdrawPayRecordRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private LiveBalanceRecordRepository liveBalanceRecordRepository;

    /**
     * 主播申请提现
     */
    public synchronized void create(LiveWithdraw withdraw) {

        WebUser user = queryChannelService.findOne(WebUser.class, withdraw.getUser().getId());
        Requires.isTrue(withdraw.getMoney() <= user.getLiveBalance(), "输入金额超过零钱余额");

        withdraw.setCreateTime(new Timestamp(System.currentTimeMillis()));
        withdraw.setStatus(1);
        liveWithdrawRepository.save(withdraw);

        user.setLiveBalance(NumberUtil.roundDown(NumberUtil.sub(user.getLiveBalance(), withdraw.getMoney()), 2).doubleValue());
        webUserRepository.save(user);

        LiveBalanceRecord record = new LiveBalanceRecord();
        record.setAnchor(user);
        record.setType(2);
        record.setCreateTime(new Timestamp(System.currentTimeMillis()));
        record.setMoney(withdraw.getMoney());
        record.setBalance(user.getLiveBalance());
        liveBalanceRecordRepository.save(record);

    }


    /**
     * 微信支付
     *
     * @param record 提现记录
     * @param status 支付状态 2、支付 3、拒绝
     * @param note   拒绝备注
     */
    public void checkWechatWithdraw(LiveWithdraw record, int status, String note) {

        Requires.isTrue(record.getStatus() == 1 && (status == 2 || status == 3), "支付状态不正确");
        Requires.hasLength(record.getUser().getOpenId(), "无法获取用户openId");

        record.setStatus(status);

        if (status == 3) {
            record.setNote(note);

            WebUser user = queryChannelService.findOne(WebUser.class, record.getUser().getId());
            user.setLiveBalance(NumberUtil.roundDown(NumberUtil.add(user.getLiveBalance(), record.getMoney()), 2).doubleValue());
            webUserRepository.save(user);

            //提现拒绝，佣金又回到余额
            LiveBalanceRecord liveRecord = new LiveBalanceRecord();
            liveRecord.setAnchor(user);
            liveRecord.setType(1);
            liveRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
            liveRecord.setMoney(record.getMoney());
            liveRecord.setBalance(user.getLiveBalance());
            liveBalanceRecordRepository.save(liveRecord);

            liveWithdrawRepository.save(record);
            return;
        }

        //生成支付凭证
        LiveWithdrawPayRecord payRecord = new LiveWithdrawPayRecord();
        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setPayMoney(record.getMoney());
        payRecord.setRecordNo(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + RandomUtil.randomNumbers(6));
        payRecord.setUser(record.getUser());
        payRecord.setStatus(1);
        payRecord.setPayType(1);
        payRecord.setPartnerTradeNo(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + RandomUtil.randomNumbers(12));

        //微信转账
        Map<String, String> reqData = new HashMap<>();
        reqData.put("partner_trade_no", payRecord.getPartnerTradeNo());
        reqData.put("openid", record.getUser().getOpenId());
        reqData.put("check_name", "NO_CHECK");
        reqData.put("amount", String.valueOf((int) NumberUtil.mul(record.getMoney(), 100)));
        reqData.put("desc", "直播分销提现");

        Map<String, String> map = new WechatRefundRequest().mmpaymkttransfers(reqData);
        log.info("微信提现信息：{}", map);

        if (map.get("flag").equals("true")) {
            payRecord.setStatus(2);
            payRecord.setPayTime(new Timestamp(System.currentTimeMillis()));
            payRecord.setPaymentNo(map.get("payment_no"));
            record.setStatus(4);
        } else {
            payRecord.setStatus(3);
            payRecord.setNote(map.get("message"));
            record.setStatus(5);
        }
        liveWithdrawRepository.save(record);
        liveWithdrawPayRecordRepository.save(payRecord);
    }

    /**
     * 银行卡支付
     *
     * @param record 提现记录
     * @param status 支付状态 2、支付 3、拒绝
     * @param note   拒绝备注
     */
    public void checkBankCardWithdraw(LiveWithdraw record, int status, String note, String image) {

        Requires.isTrue(record.getStatus() == 1 && (status == 2 || status == 3), "支付状态不正确");
        record.setStatus(status);

        if (status == 3) {

            WebUser user = queryChannelService.findOne(WebUser.class, record.getUser().getId());
            user.setLiveBalance(NumberUtil.roundDown(NumberUtil.add(user.getLiveBalance(), record.getMoney()), 2).doubleValue());
            webUserRepository.save(user);

            //拒绝 返回给直播余额
            LiveBalanceRecord liveRecord = new LiveBalanceRecord();
            liveRecord.setAnchor(user);
            liveRecord.setType(1);
            liveRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
            liveRecord.setMoney(record.getMoney());
            liveRecord.setBalance(user.getLiveBalance());
            liveBalanceRecordRepository.save(liveRecord);

            record.setNote(note);
            liveWithdrawRepository.save(record);
            return;
        }

        //生成支付凭证
        LiveWithdrawPayRecord payRecord = new LiveWithdrawPayRecord();
        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setPayMoney(record.getMoney());
        payRecord.setRecordNo(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN) + RandomUtil.randomNumbers(6));
        payRecord.setUser(record.getUser());
        payRecord.setStatus(2);
        payRecord.setPayType(2);

        payRecord.setBankCardNo(record.getBankCardNo());
        payRecord.setBankName(record.getBankName());
        payRecord.setBankSubBranch(record.getBankSubBranch());
        payRecord.setImage(image);
        liveWithdrawPayRecordRepository.save(payRecord);

        record.setRecord(payRecord);
        record.setStatus(4);
        liveWithdrawRepository.save(record);

    }
}
